<template>
  <el-dialog
    v-model="state.dialogVisible"
    :append-to-body="true"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    :destroy-on-close="true"
    top="5vh"
    :modal="model"
    :title="title"
    :width="width"
  >
    <div style="max-height: 360px; padding: 0px; overflow: auto">
      <el-tree
        ref="treeRef"
        :check-strictly="true"
        :data="treeOptions.dataList"
        :default-expanded-keys="state.treeExpanderKeys"
        highlight-current
        lazy
        :load="lazyLoadNode"
        node-key="id"
        :props="treeOptions.props"
        :show-checkbox="false"
      />
    </div>
    <template #footer>
      <el-button icon="circle-close" type="warning" @click="close">
        取消
      </el-button>
      <el-button icon="circle-check" type="primary" @click="save">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>
<script setup name="TreeNodePicker">
import { querySystemTreeNode } from "@/api/admin/system/systemtree/";
import { useTree } from "@/hooks/tree";

const props = defineProps({
  title: {
    type: String,
    default: "选择节点"
  },
  width: {
    type: String,
    default: "20%"
  },
  model: {
    type: Boolean,
    default: true
  },
  treeExpanderKeys: {
    type: Array,
    default: function () {
      return [];
    }
  }
});
const emits = defineEmits({
  change: payload => {
    return payload;
  }
});

const treeRef = ref(null);

const state = reactive({
  treeExpanderKeys: [].concat(props.expanderKeys),
  dialogVisible: false
});

const treeOptions = reactive({
  queryForm: { treeCode: "", pid: "" },
  autoLoad: false,
  props: {
    children: "children",
    label: "text",
    isLeaf: "leaf"
  },
  queryFunction: querySystemTreeNode
});

const { queryTreeData, filterNode, lazyLoadNode } = useTree(treeOptions);

const show = row => {
  const params = {};
  if (row.treeId) {
    params.treeId = row.treeId;
  }
  if (row.treeCode) {
    params.treeCode = row.treeCode;
  }
  if (row.pid) {
    params.pid = row.pid;
  }
  treeOptions.loading = true;
  filterNode(params);
  state.dialogVisible = true;
};

const close = () => {
  treeOptions.dataList = [];
  state.treeExpanderKeys = [];
  state.dialogVisible = false;
};

const save = () => {
  const node = treeRef.value.getCurrentNode();
  emits("change", node);
  close();
};

defineExpose({
  save,
  show,
  close
});
</script>
<style lang="scss" scoped></style>
